package com.jamie.order.service;

import cn.hutool.core.bean.BeanUtil;
import com.jamie.api.account.AccountService;
import com.jamie.api.dto.OrderDTO;
import com.jamie.api.order.OrderService;
import com.jamie.order.domain.Order;
import com.jamie.order.mapper.OrderMapper;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jamie
 * @date 2020/3/31
 */
@RestController
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AccountService accountService;

    private static final Map<String, Integer> COMMODITY_PRICE;

    static {
        COMMODITY_PRICE = new HashMap<>();
        COMMODITY_PRICE.put("product-1", 2);
        COMMODITY_PRICE.put("product-2", 3);
    }

    @Override
    public OrderDTO create(String userId, String commodityCode, int orderCount) {
        int orderMoney = calculate(commodityCode, orderCount);

        accountService.debit(userId, orderMoney);

        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(orderMoney);

        // INSERT INTO orders ...
        orderMapper.insert(order);
        if ("product-1".equals(commodityCode)) {
            throw new RuntimeException("故意抛出异常，测试seata");
        }
        return BeanUtil.copyProperties(order, OrderDTO.class);
    }

    private int calculate(String commodityCode, int orderCount) {
        return orderCount * COMMODITY_PRICE.get(commodityCode);
    }
}
